package com.jiuyou.clientController.member;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import cn.hutool.json.JSONUtil;

import com.jiuyou.clientController.base.ClientBaseController;
import com.ruoyi.clerkBalance.service.IClerkBalanceService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.Member;
import com.ruoyi.common.core.domain.entity.StoreUser;
import com.ruoyi.common.core.domain.entity.StoreUserRole;
import com.ruoyi.common.core.domain.model.LoginMember;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.img.ImgUtil;
import com.ruoyi.common.utils.tencentCos.CosAppendObject;
import com.ruoyi.common.utils.tencentCos.CosConstants;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.web.service.MemberTokenService;
import com.ruoyi.member.service.IMemberService;
import com.ruoyi.memberSer.domain.MemberSer;
import com.ruoyi.memberSer.service.IMemberSerService;
import com.ruoyi.shape.domain.Shape;
import com.ruoyi.shape.domain.ShapeUser;
import com.ruoyi.shape.service.IShapeService;
import com.ruoyi.shape.service.IShapeUserService;
import com.ruoyi.store.domain.Store;
import com.ruoyi.store.service.IStoreUserRoleService;
import com.ruoyi.storeUser.service.IStoreUserService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.wechat.AES;
import com.ruoyi.wechat.util.CommonUtil;
import com.ruoyi.wechat.util.ConstantWeChat;
import com.ruoyi.wechat.util.TokenUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chengliang
 * @date 2021/5/20
 **/
@RestController
@RequestMapping("/client/member")
public class MemberRegisterClientController extends ClientBaseController {
    @Autowired
    private IMemberService memberService;

    @Autowired
    private MemberTokenService tokenService;

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IMemberSerService memberSerService;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    private CommonUtil commonUtil;
    @Autowired
    private IClerkBalanceService clerkBalanceService;
    @Autowired
    private IStoreUserService storeUserService;
    @Autowired
    private IStoreUserRoleService storeUserRoleService;
    @Autowired
    private IShapeService shapeService;

    @Autowired
    private IShapeUserService shapeUserService;

    /**
     * 是否显示关注公众号
     * @return
     * @throws Exception
     */
    @RequestMapping("/showFollowSer")
    public AjaxResult showFollowSer() {
        JSONObject jsonObject=new JSONObject();
        Long memberid=getLoginMemberId();
        String showFlag="N";
        if(null!=memberid){
            Member member=memberService.selectMemberById(memberid);
            String unionId=  member.getUnionId();
            MemberSer memberSer= memberSerService.selectMemberSerByUinonId(unionId);
            if(null==memberSer||(memberSer.getSubscribe().compareTo(0L)==0)){
                showFlag="Y";
            }
        }else{
            AjaxResult.unLogin();
        }
        jsonObject.put("showFlag",showFlag);
        return AjaxResult.success(jsonObject);
    }
    /**
     * 进来获取此人的OpenId回传
     */
//    @ApiOperation("获取openid")
    @RequestMapping("/getOpenId")
    public Map getOpenId(String code,String openId) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        map.put("exist",false);
        Member exist=null;
        String unionid=null;
        if(!StringUtils.isEmpty(openId)) {
            //有openid已经授权过
            exist=memberService.selectMemberByOpenId(openId);
            storeBelow(exist.getId(),"create");//绑定为下级二维码
        }
        if(null==exist){
            //手机号注册方式
            String content = memberService.converWechatOpenId(code);
            JSONObject jsonObject = JSON.parseObject(content);
            if (jsonObject.get("session_key") == null || jsonObject.get("openid") == null) {
                throw new Exception();
            }
            openId = jsonObject.getString("openid");
            unionid=jsonObject.getString("unionid");

            exist= memberService.selectMemberByOpenId(openId);
        }

        if(null != exist){
            String token = tokenService.createToken(new LoginMember(exist));
            map.put("success",true);
            map.put("member",exist);
            map.put("exist",true);
            map.put("token",token);
            map.put("openId",openId);
            return map;
        }

        Member member = new Member();
        member.setOpenId(openId);
        member.setNickName("陌生用户");
        member.setUnionId(unionid);
        memberService.insertMember(member);

        storeBelow(member.getId(),"create");//绑定为下级二维码

        Member regist = memberService.selectMemberById(member.getId());
        String token = tokenService.createToken(new LoginMember(regist));
        map.put("member",regist);
        map.put("token",token);
        map.put("success",true);
        map.put("openId",openId);
        return map;
    }


    /**
     * 刷新绑定下级二维码
     * */
    @RequestMapping("/refreshStoreBelow")
    public AjaxResult refreshStoreBelow(){
        Long loginMemberId = tokenService.getLoginMemberId();

        storeBelow(loginMemberId,"refresh");//绑定为下级二维码
        Member regist = memberService.selectMemberById(loginMemberId);

        return AjaxResult.success(regist);
    }

    /**
     * 获取 绑定为下级二维码图片
     * @return
     */
    public String storeBelow(Long memberId,String type){
        Member member=memberService.selectMemberById(memberId);

        if(type.equals("create")){
            String belowImageUrl=member.getBelowImageUrl();
            if(!StringUtils.isEmpty(belowImageUrl)){
                return belowImageUrl;
            }
        }

        System.out.println("tangyin345");
        //long userId = getLoginStoreUserId();
        String APPKEY="YQS_C";
        String requrl= serverConfig.getUrl();
        JSONObject param=new JSONObject();
        String qrcodePage="";
        String scene="";
        String page="";
        //图书，进入章节目录
        scene="bindMemberId="+memberId;
        page="pages/UCenter/index/index";
        param.put("scene",scene);
        param.put("page",page);
        qrcodePage=page+"?"+scene;
        String pro_env=sysConfigService.selectConfigByKey(DicConstants.PRO_ENV.getCode());
        if(null==pro_env){
            return null;
        }
//        param.put("env_version","develop");//正式版为 "release"，体验版为 "trial"，开发版为 "develop"
//        param.put("check_path",false);
        if(DicConstants.SYS_Y.getCode().equals(pro_env)){
            System.out.println("正式");
            //正式环境
            param.put("env_version","release");//正式版为 "release"，体验版为 "trial"，开发版为 "develop"
        }else{
            System.out.println("体验");
            //测试参数，体验版使用，不要在正式使用
            param.put("env_version","trial");//正式版为 "release"，体验版为 "trial"，开发版为 "develop"
            param.put("check_path",false);
        }
        String codeName=memberId+"_commission_"+ IdUtils.fastUUID();
        String xml = JSONObject.toJSONString(param);
        String requestUrl= ConstantWeChat.GET_WX_ACODE_UNLIMIT.replace("#ACCESS_TOKEN#", tokenUtil.getToken(APPKEY).getAccessToken());
        JSONObject resultR= commonUtil.doPostFile(requestUrl,xml,codeName,requrl);
        System.out.println(resultR.containsKey("imgUrl"));
        if(resultR.containsKey("imgUrl")){
            String imgUrl=resultR.getString("imgUrl");
            String fileAbsolutePath=resultR.getString("fileAbsolutePath");

            Member memberUpdate = new Member();
            memberUpdate.setId(memberId);
            memberUpdate.setBelowImageLocal(fileAbsolutePath);
            memberUpdate.setBelowImageUrl(imgUrl);
            memberUpdate.setBelowPage(qrcodePage);
            memberService.updateMember(memberUpdate);
            return imgUrl;
        }
        return null;
    }


    /**
     * 进来获取此人的OpenId回传
     */
    @RequestMapping("/auto-login")
    public Map autoLogin(String openId) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        map.put("exist",false);

        Member m = new Member();
        m.setOpenId(openId);
        List<Member> members = memberService.selectMemberList(m);
        map.put("success",true);
        if(members.size()>0){
            Member member = members.get(0);
            String token = tokenService.createToken(new LoginMember(member));
            map.put("member",member);
            map.put("token",token);
            map.put("exist",true);
        }
        return map;
    }
    /**
     * 检测当前用户token是否过期
     */
   /* @RequestMapping("/check-login")
    public Map<String,Object> checkLogin(String openId ,String code) {
        Map map = new LinkedHashMap(3);
        map.put("online",false);
        map.put("regist",false);
        LoginMember loginUser = tokenService.getLoginMember();

        if(loginUser != null){
            tokenService.verifyToken(loginUser);
            map.put("online",true);
            map.put("regist",true);
            return map;
        }

        Member member = memberService.selectMemberByOpenId(openId);
        if(member != null){
            map.put("online",false);
            map.put("regist",true);
            map.put("memeber",member);
        }


        return map;

    }*/

    /**
     * 进来获取此人的OpenId回传
     */
    @RequestMapping("/register")
    public Map register(String encryptedData,String iv, String code) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("exist",false);


        String content = memberService.converWechatOpenId(code);
        JSONObject jsonObject = JSON.parseObject(content);
        if (jsonObject.get("session_key") == null || jsonObject.get("openid") == null) {
            throw new CustomException("注册失败");
        }
        String session_key = jsonObject.get("session_key").toString();
        String phoneStr = AES.wxDecrypt(encryptedData, session_key, iv);
        cn.hutool.json.JSONObject phoneJson = JSONUtil.parseObj(phoneStr);
        //没有区号的手机号
        if(phoneJson.get("purePhoneNumber") == null){
            throw new CustomException("注册失败");
        }
        map.put("phone",phoneJson.get("purePhoneNumber").toString());
        Member m = new Member();
        m.setOpenId(jsonObject.getString("openid"));

        //先根据openId看看有没有此人
//        List<Member> exist = memberService.selectMemberList(m);
        Member exist = memberService.selectMemberByOpenIdOrPhone(jsonObject.getString("openid"),phoneJson.getStr("purePhoneNumber"));
        if(exist!=null){
            map.put("exist",true);
            exist.setOpenId(jsonObject.getString("openid"));
            memberService.updateMember(exist);
            String token = tokenService.createToken(new LoginMember(exist));
            map.put("member",exist);
            map.put("token",token);
            return map;
        }
        m.setPhone(phoneJson.get("purePhoneNumber").toString());

        memberService.insertMember(m);
        List<Member> members = memberService.selectMemberList(m);
        if(members.size()>0){
            Member member = members.get(0);
            String token = tokenService.createToken(new LoginMember(member));
            map.put("member",member);
            map.put("token",token);
            map.put("success",true);
        }
        return map;
    }

    //刷新用户手机号
    @RequestMapping("/flushPhone")
    public Map flushPhone(String encryptedData,String iv, String code) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("exist",false);
        String content = memberService.converWechatOpenId(code);
        JSONObject jsonObject = JSON.parseObject(content);
        if (jsonObject.get("session_key") == null || jsonObject.get("openid") == null) {
            throw new CustomException("注册失败");
        }
        String session_key = jsonObject.get("session_key").toString();
        String phoneStr = AES.wxDecrypt(encryptedData, session_key, iv);
        cn.hutool.json.JSONObject phoneJson = JSONUtil.parseObj(phoneStr);
        //没有区号的手机号
        if(phoneJson.get("purePhoneNumber") == null){
            throw new CustomException("注册失败");
        }
        map.put("phone",phoneJson.get("purePhoneNumber").toString());
        //默认此人一定存在
        //根据openID查找
        Member member = memberService.selectMemberByOpenId(jsonObject.getString("openid"));
        if(null == member){
            throw new ServiceException("用户不存在");
        }
        Member memberUpdate=new Member();
        memberUpdate.setPhone(phoneJson.get("purePhoneNumber").toString());
        memberUpdate.setId(member.getId());
        member.setPhone(phoneJson.get("purePhoneNumber").toString());
        map.put("exist",true);
        memberService.updateMember(memberUpdate);
        String token = tokenService.createToken(new LoginMember(member));
        map.put("member",member);
        map.put("token",token);
        map.put("success",true);
        return map;
    }


    /**
     * 修改用户基本信息
     */
    @PostMapping("/update/basic/info")
    public AjaxResult updateBasicInfo(@RequestBody Map<String, Object> paramMap) {
        String headImgUrl = String.valueOf(paramMap.get("headImgUrl"));  //用户头像
        String nickName = StringUtils.toStringIfNull(paramMap.get("nickName"));  //昵称
//        Integer gender = Integer.valueOf(String.valueOf(paramMap.get("gender")));  //性别
        Long storeUserId = Long.valueOf(String.valueOf(paramMap.get("storeUserId")));  //上级 门店或员工id
        Long bindMemberId = Long.valueOf(String.valueOf(paramMap.get("bindMemberId")));  //上级 用户id

        Long loginMemberId = tokenService.getLoginMemberId();

        String fileName = DateUtils.dateTime() +"-"+IdUtils.fastUUID()+"-"+DigestUtils.md5Hex(String.valueOf(loginMemberId)) + ".jpg"; //文件名
        // 上传文件路径
        String uploadDir = RuoYiConfig.getUploadPath();
        String filePath="/headImg";
        String fileAbsolutePath = uploadDir + filePath +"/"+ fileName;
        try {

            // 读取头像图片
            BufferedImage bufferedImage = ImgUtil.loadImageUrl(headImgUrl, false);
            // 输出
            File file = new File(fileAbsolutePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            ImageIO.write(bufferedImage, "jpg", file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String headImg = serverConfig.getUrl() + Constants.RESOURCE_PREFIX + "/upload/headImg/" + fileName;
        if(DicConstants.SYS_Y.getCode().equals(configService.selectConfigByKey("cententOSS"))){
            Map<String, String> map = new HashMap<>(4);
            map.put("secretKey",configService.selectConfigByKey("secretKey"));
            map.put("secretId",configService.selectConfigByKey("secretId"));
            map.put("area",configService.selectConfigByKey("area"));
            map.put("bucketName",configService.selectConfigByKey("bucketName"));
            //开启腾讯oss
            headImg= CosAppendObject.AppendObjectFromLocal(map,fileName,fileAbsolutePath,"upload/"+filePath);
        }
        Member member = new Member();
        member.setId(loginMemberId);
        member.setHeadImg(headImg);
        member.setNickName(nickName);
        member.setStoreUserId(storeUserId);
        member.setParentMemberId(bindMemberId);
        memberService.updateMember(member);
        LoginMember loginMember = tokenService.getLoginMember();
        loginMember.setMember(member);
        tokenService.setloginMember(loginMember);

        //有上级，推广获取佣金
        if(storeUserId != null){
            StoreUser storeUser= storeUserService.selectStoreUserById(storeUserId);
            Long storeId = storeUser.getStoreId();
            if(storeId == null){
                StoreUserRole storeUserRole = new StoreUserRole();
                storeUserRole.setStoreUserId(storeUserId);
                List<StoreUserRole> StoreUserRoleList = storeUserRoleService.selectStoreUserRoleList(storeUserRole);
                storeId = StoreUserRoleList.get(0).getStoreId();
            }
            String push_member_money = configService.selectConfigByKey("push_member_money");//员工推广佣金
            BigDecimal money = new BigDecimal(push_member_money);
            //项目佣金
            clerkBalanceService.handleBalance(storeId,storeUserId,money,DicConstants.HANDLE_BALANCE_ADD.getCode(),"推广收入","推广用户ID:"+loginMemberId,DicConstants.BUSTYPE_BALANCE_PUSH.getCode(),"push");
        }
        return AjaxResult.success(member);
    }


   /* @RequestMapping("/reload")
    public Member reload(){
        try {
            LoginMember loginMember = tokenService.getLoginMember();
            if(loginMember == null){
                return null;
            }
            return memberService.selectMemberById(loginMember.getMember().getId());
        }catch (Exception e){
            return null;
        }

    }
    @RequestMapping("/loginout")
    public void loginout(){
        Long id = tokenService.getLoginMemberId();
        memberService.loginOut(id);
        tokenService.loginOut();
    }
*/
    @RequestMapping("/remove-token")
    public void removeToken(HttpServletRequest request){
        tokenService.delloginMember(request);
    }

    /**
     * 获取最新用户信息
     * @return
     */
    @PostMapping("/getMember")
    public AjaxResult getMember() {
        Long loginMemberId = tokenService.getLoginMemberId();
        if(null==loginMemberId){
            return AjaxResult.error("获取失败01");
        }
        Member memberData=memberService.selectMemberById(loginMemberId);
        return AjaxResult.success(memberData);
    }


    /**
     * 添加用户选择手型或脸型
     * */
    @RequestMapping("/createUserShape")
    public AjaxResult createUserShape(Long shapeId,Long type){
        Long loginMemberId = tokenService.getLoginMemberId();
        System.out.println("tttgdd");
        System.out.println(loginMemberId);
        if(null==loginMemberId){
            return AjaxResult.error("获取失败01");
        }

        ShapeUser shapeUser = new ShapeUser();
        shapeUser.setShapeId(shapeId);
        shapeUser.setUserId(loginMemberId);
        shapeUser.setType(type);
//        //shapeUser.setType(shapeOne.getType());
        shapeUserService.insertShapeUser(shapeUser);

        return AjaxResult.success();
    }

    /**
     * 添加用户选择手型或脸型
     * */
   /* @PostMapping("/createUserShape")
    public AjaxResult create(Long shapeId){
        if(shapeId == null){
            return AjaxResult.error("shapeId不能为空");
        }
        Shape shapeOne = shapeService.selectShapeById(shapeId);
        if(shapeOne == null){
            return AjaxResult.error("没有这个手型或脸型");
        }

        Long loginMemberId = tokenService.getLoginMemberId();

        ShapeUser shapeUser = new ShapeUser();
        shapeUser.setShapeId(shapeId);
        shapeUser.setUserId(loginMemberId);
        shapeUser.setType(shapeOne.getType());
        shapeUserService.insertShapeUser(shapeUser);

        return AjaxResult.success();
    }*/
}

